package cn.edu.tju.elm.task;

import cn.edu.tju.elm.model.VirtualWallet;
import cn.edu.tju.elm.model.WalletTransaction;
import cn.edu.tju.elm.model.TransactionType;
import cn.edu.tju.elm.repository.VirtualWalletRepository;
import cn.edu.tju.elm.repository.WalletTransactionRepository;
import cn.edu.tju.elm.service.CreditService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Component
public class OverdueCheckTask {

    private static final Logger logger = LoggerFactory.getLogger(OverdueCheckTask.class);

    @Autowired
    private VirtualWalletRepository walletRepository;

    @Autowired
    private WalletTransactionRepository transactionRepository;

    @Autowired
    private CreditService creditService;

    /**
     * 每天凌晨2点执行逾期检查
     */
    @Scheduled(cron = "0 0 2 * * ?")
    @Transactional
    public void checkOverduePayments() {
        logger.info("开始执行逾期检查任务...");
        
        try {
            // 处理信用服务的逾期检查
            creditService.processOverdueCheck();
            logger.info("逾期检查任务执行完成");
        } catch (Exception e) {
            logger.error("逾期检查任务执行失败", e);
        }
    }

    /**
     * 检查VIP到期 - 每小时执行一次
     */
    @Scheduled(cron = "0 0 * * * ?")
    @Transactional
    public void checkVipExpiration() {
        logger.info("开始执行VIP到期检查任务...");
        
        try {
            List<VirtualWallet> expiringVipWallets = walletRepository.findAll().stream()
                    .filter(wallet -> wallet.isVip() && 
                            wallet.getVipExpireTime() != null && 
                            wallet.getVipExpireTime().isBefore(LocalDateTime.now()))
                    .toList();

            for (VirtualWallet wallet : expiringVipWallets) {
                // 取消VIP状态
                wallet.setVipStatus(false, null);
                walletRepository.save(wallet);
                
                logger.info("用户 {} 的VIP状态已到期，自动取消", wallet.getUserId());
            }
            
            logger.info("VIP到期检查任务执行完成，处理了 {} 个用户", expiringVipWallets.size());
        } catch (Exception e) {
            logger.error("VIP到期检查任务执行失败", e);
        }
    }
}